#!/usr/bin/envpython
# -*-coding:UTF-8-*-
'''
@File    :   department_help.py
@Contact :   308711822@qq.com
@License :   (C) Copyright 2021-2225, Personal exclusive right.

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
2023/5/30 11:40   小钟同学      1.0         None
'''


def get_name(data, item):
    """
    递归获取名称
    """
    # 如果 parent_id 等于自己的 id，则说明已经遍历到了根节点，返回节点名称
    if item['parent_id'] == item['department_id']:
        return item['name']
    # 否则递归获取父节点名称
    for d in data:
        if d['department_id'] == item['parent_id']:
            return get_name(data, d) + '/' + item['name']
    return item['name']


def convert_data(data):
    """
    转换数据
    """
    result = []
    for item in data:
        name = get_name(data, item)
        result.append({'department_id': item['department_id'], 'name': name})
    return result




def tree_convert_data(data, parent_id=0):
    """
    转换数据
    """
    result = []
    pre_id = None
    for item in data:
        if item['parentId'] == parent_id:
            # 计算 preId 和 nextId
            item['preId'] = pre_id
            if len(result) > 0:
                result[-1]['nextId'] = item['departmentId']
            pre_id = item['departmentId']
            # 递归转换子节点
            children = tree_convert_data(data, item['departmentId'])
            item['children'] = children if len(children) > 0 else None
            # 计算 selfAndAllChildrenIdList
            item_ids = [item['departmentId']]
            if children is not None:
                for child in children:
                    item_ids += child['selfAndAllChildrenIdList']
            item['selfAndAllChildrenIdList'] = item_ids
            result.append(item)
    return result